package com.example.demo.token;

import lombok.Data;

import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 马拉圈
 * Date: 2023-10-20
 * Time: 22:21
 */
@Data
public class AccessToken {

    private String token;

    private long expireTime;//有效期限


    volatile private static AccessToken accessToken = null;

    public void setExpireTime(long expireIn) {
        // 设置有效期限的时候的时间戳
        this.expireTime = System.currentTimeMillis() + expireIn * 1000;
    }

    public boolean isExpired() {
        return System.currentTimeMillis() > this.getExpireTime();
    }


    private static void setAccessToken(String appId, String appSecret) {
        if(accessToken == null) {
            accessToken = new AccessToken();
        }
        Map<String, Object> map = TokenUtils.getAccessTokenMap(appId, appSecret);
        accessToken.setToken((String) map.get("access_token"));
        accessToken.setExpireTime((Integer) map.get("expires_in"));
    }

    public static AccessToken getAccessToken(String appId, String appSecret) {
        if(accessToken == null || accessToken.isExpired()) {
            synchronized (AccessToken.class) {
                if(accessToken == null || accessToken.isExpired()) {
                    setAccessToken(appId, appSecret);
                }
            }
        }
        return accessToken;
    }

}
